package com.pattern.prototype;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.*;

/**
 * 深克隆 通过序列化（Serialization）等方式来进行深度克隆
 * @author LYao15
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PrototypePattern1 implements Serializable {
    private User user;
    private int age;

    public PrototypePattern1(User user){
        this.user = user;
    }

    /**
     * 通过序列化进行深克隆
     * @return
     */
    public PrototypePattern1 deepClone() throws IOException, ClassNotFoundException {

        //序列化 成流
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        //使用对象输出流
        ObjectOutputStream outputStream = new ObjectOutputStream(bao);
        outputStream.writeObject(this);

        //反序列化生成对象
        ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(bai);

        PrototypePattern1 o = (PrototypePattern1) objectInputStream.readObject();
        return o;
    }
}
